<template>
	<div class="_wz_sendNoticeAdd">
		<Steps :current="current" style="width: 80%;margin: auto;">
			<Step title="基本信息"></Step>
			<Step title="人员选择"></Step>
		</Steps>
		<div style="height: 100%;overflow: auto;">
			<div v-if="current == 0" style="padding: 10px;">
				<Form ref="formAdd" :model="formData" label-position="right" :label-width="110" :rules="ruleValidate">
					<FormItem label="通知标题" prop="noticeTitle">
						<i-input v-model="formData.noticeTitle" placeholder="请填写通知标题" clearable />
					</FormItem>
					<FormItem label="通知等级" prop="noticeLv">
						<i-select v-model.number="formData.noticeLv" filterable placeholder="请选择通知等级" clearable>
							<Option :value="1">普通</Option>
							<Option :value="2">重要</Option>
							<Option :value="3">紧急</Option>
						</i-select>
					</FormItem>

					<FormItem label="运输企业" prop="deptUuid">
						<i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable>
							<Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
						</i-select>
					</FormItem>
					<FormItem label="回复状态" prop="noticeReplyType">
						<i-switch v-model.number="formData.noticeReplyType" :false-value="0" :true-value="1">
							<span slot="open">开</span>
							<span slot="close">关</span>
						</i-switch>
					</FormItem>
					<FormItem label="通知附件" prop="multipartFile">
						<Upload name="multipartFile" :before-upload="handleUpload" action="">
							<Button type="primary" icon="ios-cloud-upload-outline">上传附件（文件支持mp4、docx）</Button>
							{{fileName}}
						</Upload>
					</FormItem>
					<FormItem label="企业下发人" prop="deptContact">
						<i-input v-model="formData.deptContact" placeholder="请填写企业下发人" clearable />
					</FormItem>
					<FormItem label="通知内容" prop="noticeContent">
            <tinymce :htmlData="formData.noticeContent" :height="500" @tinymceData="val => formData.noticeContent = val"></tinymce>
					</FormItem>
				</Form>
			</div>
			<div v-else class="_wz_sendNoticeAdd" style="padding: 10px;">
				<Form :model="formData" label-position="right" :label-width="120">
					<FormItem label="发布类型" class="ivu-form-item-required">
						<RadioGroup v-model.number="noticePublishType">
							<Radio :label="0">按身份发布</Radio>
							<Radio :label="1">按人员发布</Radio>
						</RadioGroup>
					</FormItem>
					<FormItem label="从业身份" class="ivu-form-item-required">
						<CheckboxGroup v-model="examPlanPublishValue" @on-change="studentTypeFun">
							<Checkbox v-for="item in personType" :label="item.code" :key="item.code">{{item.value}}</Checkbox>
						</CheckboxGroup>
					</FormItem>
				</Form>
				<div style="height: 100%;overflow: auto;">
					<wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
				</div>
			</div>
		</div>

		<div class="demo-drawer-footer">
			<Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
			<Button style="margin-right: 8px" type="primary" v-if="current != 0" @click="Previous">上一步</Button>
			<Button style="margin-right: 8px" type="primary" v-if="current == 0" @click="nextFun">下一步</Button>
			<Button type="primary" @click="addSubmit" v-if="current != 0">提交</Button>
		</div>
	</div>
</template>
<script>

	import wzTbale from "../../../components/table/table";
  import tinymce from "../../../components/table/tinymce";

	export default {
		components: {
			wzTbale,//列表
      tinymce,
		},
		props: ["selectData"],//接收来自父组件的数据
		data() {
			return {
        editorOption: {
          placeholder: "请填写通知内容",
          modules:{
            toolbar:[
              ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
              // ['blockquote', 'code-block'],     //引用，代码块
              [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
              [{ 'script': 'sub'}, { 'script': 'super' }],   // 上下标
              [{ 'indent': '-1'}, { 'indent': '+1' }],     // 缩进
              [{ 'direction': 'rtl' }],             // 文本方向
              // [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
              // [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
              [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
              // [{ 'font': [] }],     //字体
              [{ 'align': [] }],    //对齐方式
              ['clean'],    //清除字体样式
              // ['image','video']    //上传图片、上传视频
            ]
          }
        },
        personType:[],//从业类型
				subDeptList: [],//运输企业
				uploadProgress: 0,//文件上传进度
				current: 0,//步骤条
				formData: {
					noticeReplyType: 0
				},//新增修改表单数据
				fileData: null,
				fileName: "",//上传前 获取本地的文件名称

				noticePublishType: 0,//选择从业类型
				examPlanPublishValue: [],//从业身份
				ruleValidate: {
					noticeTitle: [
						{required: true, message: '请填写通知标题', trigger: 'blur'}
					],
					deptUuid: [
						{required: true, message: '请选择运输企业', trigger: 'blur'}
					],
					noticeLv: [
						{type: 'number', required: true, message: '请选择通知等级', trigger: 'blur'}
					],
					noticeReplyType: [
						{type: 'number', required: true, message: '请选择回复状态', trigger: 'blur'}
					],
					deptContact: [
						{required: true, message: '请填写企业下发人', trigger: 'blur'}
					],
					noticeContent: [
						{required: true, message: '请填写通知内容', trigger: 'blur'}
					],
				},
				tableData: {
					height: '100%',//表格高度 auto
					page: false,//分页是否使用
					columns: [//表头数据
						{type: 'index', width: 70, align: 'center', title: '序号'},
						{title: '从业人员', key: 'name', minWidth: 100},
						{title: '从业类型', key: 'typeName', minWidth: 100},
						{title: '联系电话', key: 'phone', minWidth: 130},
						{title: '驾乘车辆', key: 'vehiclePlate', minWidth: 120},
						{title: '身份证号', key: 'identifyNum', minWidth: 180},
					],
					dataList: [],
				},
			}
		},
		beforeCreate() {//beforeCreate创建前状态

		},
		created() {//created创建完毕状态

		},
		beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

		},
		mounted() {//mounted 挂载结束状态
			let that = this;


			//运输企业
			that.axios.post(that.apiUrl.coreDeptCoreDeptList, {}).then(res => {
				if (!!res) {
					that.subDeptList = res.data.data;
					if (!!!that.selectData.id) {//添加
						that.formData.deptUuid = that.subDeptList[0].uuid;
					}
				}
			}).catch(err => {
				console.log("失败", err)
			})
			//从业类型
			that.axios.post(that.apiUrl.systemDictSystemDictList, {type: 'person_type'}).then(res => {
				if (!!res) {
					that.personType = res.data.data;
					let userId = [];
					if (!!!that.selectData.id) {//添加
						res.data.data.forEach(function (k, i) {
							userId.push(k.code)
						})
						that.examPlanPublishValue = userId;
					} else {//修改
						if (!!that.selectData.noticePublishValueCode && that.selectData.noticePublishValueCode.length > 0) {
							that.examPlanPublishValue = that.selectData.noticePublishValueCode.split(',');//从业身份
						}
						that.noticePublishType = that.selectData.noticePublishType;//发布类型

						//选中学员
						if (!!that.selectData.noticePublishDriverValue && that.selectData.noticePublishDriverValue.length > 0) {
							that.selectData.noticePublishDriverValue = that.selectData.noticePublishDriverValue.split(',');
						}

						that.formData = that.selectData;
						that.studentTypeFun();
					}
				}
			}).catch(err => {
				console.log('失败', err);
			})


		},
		methods: {//执行的方法
			Previous() {//上一步
				if (this.current == 0) {
					return false;
				} else {
					this.current = 0;
				}
			},
			nextFun() {//下一步
				let that = this;
				that.$refs["formAdd"].validate((valid) => {
					if (valid) {
						that.current = 1;
						that.studentTypeFun();
					} else {
						that.$Message.error('请正确填写表单');
						return false;
					}
				})
			},
			//选择文件
			handleUpload(file) {
				let that = this;
				let type = file.name.substr((file.name.lastIndexOf(".") + 1));
				if (type == "MP4" || type == "mp4") {//视频
					that.formData.noticeFileType = 1;
					that.fileData = file;
					that.fileName = file.name;
				} else if (type == "DOCX" || type == "docx") {//word
					that.formData.noticeFileType = 2;
					that.fileData = file;
					that.fileName = file.name;
				} else {
					that.$Message.error('您上传的文件类型不匹配');
					return false;
				}
				return false;
			},
			studentTypeFun() {//从业类型变动  加载表格
				let that = this;
				//加载人员
				if (!!that.examPlanPublishValue && that.examPlanPublishValue.length > 0) {
					that.axios.post(that.apiUrl.coreDriverCoreDriverList, {
						typeList: that.examPlanPublishValue,
						binding: 1,
						deptUuid: that.formData.deptUuid
					}).then(res => {//加载所有数据
						if (!!res) {
							if (!!!that.selectData.id) {//添加
								that.tableData.dataList = res.data.data;//返回数据
							} else {
								if (!!that.formData.noticePublishDriverValue) {
									res.data.data.forEach(function (k, i) {
										that.formData.noticePublishDriverValue.forEach(function (ko, io) {
											if (k.uuid == ko) {
												k._checked = true;
											}
										})
									})
								}
								that.tableData.dataList = res.data.data;//返回数据
							}
						}
					}).catch(err => {
						console.log('失败', err);
					})
				} else {
					that.tableData.dataList = [];
				}
			},
			//提交
			addSubmit() {
				var that = this;
				//extractName(数据源,所选数据,参数类型)
				that.formData.noticePublishValueName = that.public.extractName(that.personType, that.examPlanPublishValue, {
					uniqueValue: 'code',
					name: 'value',
				}).value.join(',')//从业身份中文


				that.formData.noticePublishValueCode = that.examPlanPublishValue.join(',');//从业身份
				that.formData.noticePublishType = that.noticePublishType;//发布类型

				let userUid = [];
				that.$refs.wzTbale.selectDataList.forEach(function (k, i) {
					userUid.push(k.uuid)
				})
				that.formData.noticePublishDriverValue = userUid.join(',');

				let data = that.formData;
				let formData = new FormData();

				for (let key in data) {
					if (data[key] != 'null' || data[key] != null || data[key] != undefined) {
						formData.append(key, data[key]);
					}
				}
				//文件
				if (!!that.fileData) {
					formData.append('multipartFile', that.fileData);
				}
				that.axios.post(that.apiUrl.webApi + "/notice/deptMessage/noticeDeptMessageSaveOrUpdate", formData, that.public.parameterUploadProgress(that)).then(res => {
          that.$Spin.hide();
					if (!!res) {
						that.$Message.success("保存成功");
						that.$emit("closeFun", true)
					}
				}).catch(err => {
					console.log('失败', err);
				})


			},

		},
		watch: {//监听
			//发布类型监听
			noticePublishType(news, old) {
				let that = this;
				if (news == 1) {//指定人员培训  去除从业类型选项  表格加载所有人的数据  加上多选
					that.tableData.columns.splice(0, 0, {type: 'selection', width: 70, align: 'center'});
				} else {//从业从业类型培训  显示从业类型  从新加载表格 无数据  去除多选
					if (that.tableData.columns[0].key != "name") {
						that.tableData.columns.splice(0, 1);//
					}
				}
			},

		},
		beforeUpdate() {//beforeUpdate 更新前状态

		},
		updated() {//updated 更新完成状态

		},
		beforeDestroy() {//beforeDestroy 销毁前状态

		},
		destroyed() {//destroyed 销毁完成状态

		}
	}
</script>
<style lang="less">
	._wz_sendNoticeAdd {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

  .ql-container{
    height: 150px;
  }
</style>
